blob: 36af637fa0e1d6f4cfa315993ec2ab77c1501a95 [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
Christian Heimes46bebee2013-06-09 19:03:31 +020092import sys
Christian Heimes6d7ad132013-06-09 18:02:55 +020093import os
94import collections
Thomas Woutersed03b412007-08-28 21:37:11 +000095
96import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000097
Antoine Pitrou04f6a322010-04-05 21:40:07 +000098from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Antoine Pitrou41032a62011-10-27 23:56:55 +020099from _ssl import _SSLContext
100from _ssl import (
101 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
102 SSLSyscallError, SSLEOFError,
103 )
Thomas Woutersed03b412007-08-28 21:37:11 +0000104from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Victor Stinner99c8b162011-05-24 12:05:19 +0200105from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100106
107def _import_symbols(prefix):
108 for n in dir(_ssl):
109 if n.startswith(prefix):
110 globals()[n] = getattr(_ssl, n)
111
112_import_symbols('OP_')
113_import_symbols('ALERT_DESCRIPTION_')
114_import_symbols('SSL_ERROR_')
115
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100116from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100117
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100118from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200119from _ssl import _OPENSSL_API_VERSION
120
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100121
Victor Stinner3de49192011-05-09 00:42:58 +0200122_PROTOCOL_NAMES = {
123 PROTOCOL_TLSv1: "TLSv1",
124 PROTOCOL_SSLv23: "SSLv23",
125 PROTOCOL_SSLv3: "SSLv3",
126}
127try:
128 from _ssl import PROTOCOL_SSLv2
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100129 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Brett Cannoncd171c82013-07-04 17:43:24 -0400130except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100131 _SSLv2_IF_EXISTS = None
Victor Stinner3de49192011-05-09 00:42:58 +0200132else:
133 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +0000134
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100135try:
136 from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
Brett Cannoncd171c82013-07-04 17:43:24 -0400137except ImportError:
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100138 pass
139else:
140 _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1"
141 _PROTOCOL_NAMES[PROTOCOL_TLSv1_2] = "TLSv1.2"
142
Christian Heimes46bebee2013-06-09 19:03:31 +0200143if sys.platform == "win32":
144 from _ssl import enum_cert_store, X509_ASN_ENCODING, PKCS_7_ASN_ENCODING
145
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000146from socket import getnameinfo as _getnameinfo
Antoine Pitrou15399c32011-04-28 19:23:55 +0200147from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000148import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +0000149import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000150import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000151
Andrew Svetlov0832af62012-12-18 23:10:48 +0200152
153socket_error = OSError # keep that public name in module namespace
154
Antoine Pitroud6494802011-07-21 01:11:30 +0200155if _ssl.HAS_TLS_UNIQUE:
156 CHANNEL_BINDING_TYPES = ['tls-unique']
157else:
158 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000159
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100160# Disable weak or insecure ciphers by default
161# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
162_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
163
Thomas Woutersed03b412007-08-28 21:37:11 +0000164
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000165class CertificateError(ValueError):
166 pass
167
168
Georg Brandl72c98d32013-10-27 07:16:53 +0100169def _dnsname_match(dn, hostname, max_wildcards=1):
170 """Matching according to RFC 6125, section 6.4.3
171
172 http://tools.ietf.org/html/rfc6125#section-6.4.3
173 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000174 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100175 if not dn:
176 return False
177
178 leftmost, *remainder = dn.split(r'.')
179
180 wildcards = leftmost.count('*')
181 if wildcards > max_wildcards:
182 # Issue #17980: avoid denials of service by refusing more
183 # than one wildcard per fragment. A survery of established
184 # policy among SSL implementations showed it to be a
185 # reasonable choice.
186 raise CertificateError(
187 "too many wildcards in certificate DNS name: " + repr(dn))
188
189 # speed up common case w/o wildcards
190 if not wildcards:
191 return dn.lower() == hostname.lower()
192
193 # RFC 6125, section 6.4.3, subitem 1.
194 # The client SHOULD NOT attempt to match a presented identifier in which
195 # the wildcard character comprises a label other than the left-most label.
196 if leftmost == '*':
197 # When '*' is a fragment by itself, it matches a non-empty dotless
198 # fragment.
199 pats.append('[^.]+')
200 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
201 # RFC 6125, section 6.4.3, subitem 3.
202 # The client SHOULD NOT attempt to match a presented identifier
203 # where the wildcard character is embedded within an A-label or
204 # U-label of an internationalized domain name.
205 pats.append(re.escape(leftmost))
206 else:
207 # Otherwise, '*' matches any dotless string, e.g. www*
208 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
209
210 # add the remaining fragments, ignore any wildcards
211 for frag in remainder:
212 pats.append(re.escape(frag))
213
214 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
215 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000216
217
218def match_hostname(cert, hostname):
219 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100220 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
221 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000222
223 CertificateError is raised on failure. On success, the function
224 returns nothing.
225 """
226 if not cert:
227 raise ValueError("empty or no certificate")
228 dnsnames = []
229 san = cert.get('subjectAltName', ())
230 for key, value in san:
231 if key == 'DNS':
Georg Brandl72c98d32013-10-27 07:16:53 +0100232 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000233 return
234 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200235 if not dnsnames:
236 # The subject is only checked when there is no dNSName entry
237 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000238 for sub in cert.get('subject', ()):
239 for key, value in sub:
240 # XXX according to RFC 2818, the most specific Common Name
241 # must be used.
242 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100243 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000244 return
245 dnsnames.append(value)
246 if len(dnsnames) > 1:
247 raise CertificateError("hostname %r "
248 "doesn't match either of %s"
249 % (hostname, ', '.join(map(repr, dnsnames))))
250 elif len(dnsnames) == 1:
251 raise CertificateError("hostname %r "
252 "doesn't match %r"
253 % (hostname, dnsnames[0]))
254 else:
255 raise CertificateError("no appropriate commonName or "
256 "subjectAltName fields were found")
257
258
Christian Heimes6d7ad132013-06-09 18:02:55 +0200259DefaultVerifyPaths = collections.namedtuple("DefaultVerifyPaths",
260 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
261 "openssl_capath")
262
263def get_default_verify_paths():
264 """Return paths to default cafile and capath.
265 """
266 parts = _ssl.get_default_verify_paths()
267
268 # environment vars shadow paths
269 cafile = os.environ.get(parts[0], parts[1])
270 capath = os.environ.get(parts[2], parts[3])
271
272 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
273 capath if os.path.isdir(capath) else None,
274 *parts)
275
276
Antoine Pitrou152efa22010-05-16 18:19:27 +0000277class SSLContext(_SSLContext):
278 """An SSLContext holds various SSL-related configuration options and
279 data, such as certificates and possibly a private key."""
280
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100281 __slots__ = ('protocol', '__weakref__')
Antoine Pitrou152efa22010-05-16 18:19:27 +0000282
283 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100284 self = _SSLContext.__new__(cls, protocol)
285 if protocol != _SSLv2_IF_EXISTS:
286 self.set_ciphers(_DEFAULT_CIPHERS)
287 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000288
289 def __init__(self, protocol):
290 self.protocol = protocol
291
292 def wrap_socket(self, sock, server_side=False,
293 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000294 suppress_ragged_eofs=True,
295 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000296 return SSLSocket(sock=sock, server_side=server_side,
297 do_handshake_on_connect=do_handshake_on_connect,
298 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000299 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000300 _context=self)
301
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100302 def set_npn_protocols(self, npn_protocols):
303 protos = bytearray()
304 for protocol in npn_protocols:
305 b = bytes(protocol, 'ascii')
306 if len(b) == 0 or len(b) > 255:
307 raise SSLError('NPN protocols must be 1 to 255 in length')
308 protos.append(len(b))
309 protos.extend(b)
310
311 self._set_npn_protocols(protos)
312
Antoine Pitrou152efa22010-05-16 18:19:27 +0000313
314class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000315 """This class implements a subtype of socket.socket that wraps
316 the underlying OS socket in an SSL context when necessary, and
317 provides read and write methods over that channel."""
318
Bill Janssen6e027db2007-11-15 22:23:56 +0000319 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000320 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000321 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
322 do_handshake_on_connect=True,
323 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100324 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000325 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000326 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000327
Antoine Pitrou152efa22010-05-16 18:19:27 +0000328 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100329 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000330 else:
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000331 if server_side and not certfile:
332 raise ValueError("certfile must be specified for server-side "
333 "operations")
Giampaolo RodolĂ 8b7da622010-08-30 18:28:05 +0000334 if keyfile and not certfile:
335 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000336 if certfile and not keyfile:
337 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100338 self._context = SSLContext(ssl_version)
339 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000340 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100341 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000342 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100343 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100344 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100345 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000346 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100347 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000348 self.keyfile = keyfile
349 self.certfile = certfile
350 self.cert_reqs = cert_reqs
351 self.ssl_version = ssl_version
352 self.ca_certs = ca_certs
353 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000354 if server_side and server_hostname:
355 raise ValueError("server_hostname can only be specified "
356 "in client mode")
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000357 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000358 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000359 self.do_handshake_on_connect = do_handshake_on_connect
360 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000361 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000362 socket.__init__(self,
363 family=sock.family,
364 type=sock.type,
365 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000366 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000367 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000368 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000369 elif fileno is not None:
370 socket.__init__(self, fileno=fileno)
371 else:
372 socket.__init__(self, family=family, type=type, proto=proto)
373
Antoine Pitrou242db722013-05-01 20:52:07 +0200374 # See if we are connected
375 try:
376 self.getpeername()
377 except OSError as e:
378 if e.errno != errno.ENOTCONN:
379 raise
380 connected = False
381 else:
382 connected = True
383
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000384 self._closed = False
385 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000386 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000387 if connected:
388 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000389 try:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100390 self._sslobj = self._context._wrap_socket(self, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +0000391 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000392 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000393 timeout = self.gettimeout()
394 if timeout == 0.0:
395 # non-blocking
396 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000397 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000398
Andrew Svetlov0832af62012-12-18 23:10:48 +0200399 except OSError as x:
Bill Janssen6e027db2007-11-15 22:23:56 +0000400 self.close()
401 raise x
Antoine Pitrou242db722013-05-01 20:52:07 +0200402
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100403 @property
404 def context(self):
405 return self._context
406
407 @context.setter
408 def context(self, ctx):
409 self._context = ctx
410 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000411
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000412 def dup(self):
413 raise NotImplemented("Can't dup() %s instances" %
414 self.__class__.__name__)
415
Bill Janssen6e027db2007-11-15 22:23:56 +0000416 def _checkClosed(self, msg=None):
417 # raise an exception here if you wish to check for spurious closes
418 pass
419
Antoine Pitrou242db722013-05-01 20:52:07 +0200420 def _check_connected(self):
421 if not self._connected:
422 # getpeername() will raise ENOTCONN if the socket is really
423 # not connected; note that we can be connected even without
424 # _connected being set, e.g. if connect() first returned
425 # EAGAIN.
426 self.getpeername()
427
Bill Janssen54cc54c2007-12-14 22:08:56 +0000428 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000429 """Read up to LEN bytes and return them.
430 Return zero-length string on EOF."""
431
Bill Janssen6e027db2007-11-15 22:23:56 +0000432 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200433 if not self._sslobj:
434 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000435 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000436 if buffer is not None:
437 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000438 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000439 v = self._sslobj.read(len or 1024)
440 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000441 except SSLError as x:
442 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000443 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000444 return 0
445 else:
446 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000447 else:
448 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000449
450 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000451 """Write DATA to the underlying SSL channel. Returns
452 number of bytes of DATA actually transmitted."""
453
Bill Janssen6e027db2007-11-15 22:23:56 +0000454 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200455 if not self._sslobj:
456 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000457 return self._sslobj.write(data)
458
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000459 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000460 """Returns a formatted version of the data in the
461 certificate provided by the other end of the SSL channel.
462 Return None if no certificate was provided, {} if a
463 certificate was provided, but not validated."""
464
Bill Janssen6e027db2007-11-15 22:23:56 +0000465 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200466 self._check_connected()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467 return self._sslobj.peer_certificate(binary_form)
468
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100469 def selected_npn_protocol(self):
470 self._checkClosed()
471 if not self._sslobj or not _ssl.HAS_NPN:
472 return None
473 else:
474 return self._sslobj.selected_npn_protocol()
475
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000476 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000477 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000478 if not self._sslobj:
479 return None
480 else:
481 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000482
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100483 def compression(self):
484 self._checkClosed()
485 if not self._sslobj:
486 return None
487 else:
488 return self._sslobj.compression()
489
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000490 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000491 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000492 if self._sslobj:
493 if flags != 0:
494 raise ValueError(
495 "non-zero flags not allowed in calls to send() on %s" %
496 self.__class__)
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200497 try:
498 v = self._sslobj.write(data)
499 except SSLError as x:
500 if x.args[0] == SSL_ERROR_WANT_READ:
501 return 0
502 elif x.args[0] == SSL_ERROR_WANT_WRITE:
503 return 0
Bill Janssen6e027db2007-11-15 22:23:56 +0000504 else:
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200505 raise
506 else:
507 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000508 else:
509 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000510
Antoine Pitroua468adc2010-09-14 14:43:44 +0000511 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000512 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000513 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000514 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000515 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000516 elif addr is None:
517 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000518 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000519 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000520
Nick Coghlan513886a2011-08-28 00:00:27 +1000521 def sendmsg(self, *args, **kwargs):
522 # Ensure programs don't send data unencrypted if they try to
523 # use this method.
524 raise NotImplementedError("sendmsg not allowed on instances of %s" %
525 self.__class__)
526
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000527 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000528 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000529 if self._sslobj:
Giampaolo RodolĂ 374f8352010-08-29 12:08:09 +0000530 if flags != 0:
531 raise ValueError(
532 "non-zero flags not allowed in calls to sendall() on %s" %
533 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000534 amount = len(data)
535 count = 0
536 while (count < amount):
537 v = self.send(data[count:])
538 count += v
539 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000540 else:
541 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000542
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000543 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000544 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000545 if self._sslobj:
546 if flags != 0:
547 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000548 "non-zero flags not allowed in calls to recv() on %s" %
549 self.__class__)
550 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000551 else:
552 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000553
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000554 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000555 self._checkClosed()
556 if buffer and (nbytes is None):
557 nbytes = len(buffer)
558 elif nbytes is None:
559 nbytes = 1024
560 if self._sslobj:
561 if flags != 0:
562 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000563 "non-zero flags not allowed in calls to recv_into() on %s" %
564 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000565 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000566 else:
567 return socket.recv_into(self, buffer, nbytes, flags)
568
Antoine Pitroua468adc2010-09-14 14:43:44 +0000569 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000570 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000571 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000572 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000573 self.__class__)
574 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000575 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000576
Bill Janssen58afe4c2008-09-08 16:45:19 +0000577 def recvfrom_into(self, buffer, nbytes=None, flags=0):
578 self._checkClosed()
579 if self._sslobj:
580 raise ValueError("recvfrom_into not allowed on instances of %s" %
581 self.__class__)
582 else:
583 return socket.recvfrom_into(self, buffer, nbytes, flags)
584
Nick Coghlan513886a2011-08-28 00:00:27 +1000585 def recvmsg(self, *args, **kwargs):
586 raise NotImplementedError("recvmsg not allowed on instances of %s" %
587 self.__class__)
588
589 def recvmsg_into(self, *args, **kwargs):
590 raise NotImplementedError("recvmsg_into not allowed on instances of "
591 "%s" % self.__class__)
592
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000593 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000594 self._checkClosed()
595 if self._sslobj:
596 return self._sslobj.pending()
597 else:
598 return 0
599
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000600 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000601 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000603 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000604
Ezio Melottidc55e672010-01-18 09:15:14 +0000605 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000606 if self._sslobj:
607 s = self._sslobj.shutdown()
608 self._sslobj = None
609 return s
610 else:
611 raise ValueError("No SSL wrapper around " + str(self))
612
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000613 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000614 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000615 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000616
Bill Janssen48dc27c2007-12-05 03:38:10 +0000617 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000618 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200619 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000620 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000621 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000622 if timeout == 0.0 and block:
623 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000624 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000625 finally:
626 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000627
Antoine Pitroub4410db2011-05-18 18:51:06 +0200628 def _real_connect(self, addr, connect_ex):
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000629 if self.server_side:
630 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000631 # Here we assume that the socket is client-side, and not
632 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000633 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000635 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000636 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200637 if connect_ex:
638 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000639 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200640 rc = None
641 socket.connect(self, addr)
642 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +0200643 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +0200644 if self.do_handshake_on_connect:
645 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +0200646 return rc
Andrew Svetlov0832af62012-12-18 23:10:48 +0200647 except OSError:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200648 self._sslobj = None
649 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000650
651 def connect(self, addr):
652 """Connects to remote ADDR, and then wraps the connection in
653 an SSL channel."""
654 self._real_connect(addr, False)
655
656 def connect_ex(self, addr):
657 """Connects to remote ADDR, and then wraps the connection in
658 an SSL channel."""
659 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000660
661 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000662 """Accepts a new connection from a remote client, and returns
663 a tuple containing that new connection wrapped with a server-side
664 SSL channel, and the address of the remote client."""
665
666 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100667 newsock = self.context.wrap_socket(newsock,
668 do_handshake_on_connect=self.do_handshake_on_connect,
669 suppress_ragged_eofs=self.suppress_ragged_eofs,
670 server_side=True)
671 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000672
Antoine Pitroud6494802011-07-21 01:11:30 +0200673 def get_channel_binding(self, cb_type="tls-unique"):
674 """Get channel binding data for current connection. Raise ValueError
675 if the requested `cb_type` is not supported. Return bytes of the data
676 or None if the data is not available (e.g. before the handshake).
677 """
678 if cb_type not in CHANNEL_BINDING_TYPES:
679 raise ValueError("Unsupported channel binding type")
680 if cb_type != "tls-unique":
681 raise NotImplementedError(
682 "{0} channel binding type not implemented"
683 .format(cb_type))
684 if self._sslobj is None:
685 return None
686 return self._sslobj.tls_unique_cb()
687
Bill Janssen54cc54c2007-12-14 22:08:56 +0000688
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689def wrap_socket(sock, keyfile=None, certfile=None,
690 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000691 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000692 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100693 suppress_ragged_eofs=True,
694 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695
Bill Janssen6e027db2007-11-15 22:23:56 +0000696 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000697 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000698 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000699 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000700 suppress_ragged_eofs=suppress_ragged_eofs,
701 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702
Thomas Woutersed03b412007-08-28 21:37:11 +0000703# some utility functions
704
705def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000706 """Takes a date-time string in standard ASN1_print form
707 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
708 a Python time value in seconds past the epoch."""
709
Thomas Woutersed03b412007-08-28 21:37:11 +0000710 import time
711 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
712
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000713PEM_HEADER = "-----BEGIN CERTIFICATE-----"
714PEM_FOOTER = "-----END CERTIFICATE-----"
715
716def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000717 """Takes a certificate in binary DER format and returns the
718 PEM version of it as a string."""
719
Bill Janssen6e027db2007-11-15 22:23:56 +0000720 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
721 return (PEM_HEADER + '\n' +
722 textwrap.fill(f, 64) + '\n' +
723 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000724
725def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726 """Takes a certificate in ASCII PEM format and returns the
727 DER-encoded version of it as a byte sequence"""
728
729 if not pem_cert_string.startswith(PEM_HEADER):
730 raise ValueError("Invalid PEM encoding; must start with %s"
731 % PEM_HEADER)
732 if not pem_cert_string.strip().endswith(PEM_FOOTER):
733 raise ValueError("Invalid PEM encoding; must end with %s"
734 % PEM_FOOTER)
735 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000736 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000738def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000739 """Retrieve the certificate from the server at the specified address,
740 and return it as a PEM-encoded string.
741 If 'ca_certs' is specified, validate the server cert against it.
742 If 'ssl_version' is specified, use it in the connection attempt."""
743
744 host, port = addr
745 if (ca_certs is not None):
746 cert_reqs = CERT_REQUIRED
747 else:
748 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200749 s = create_connection(addr)
750 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000752 dercert = s.getpeercert(True)
753 s.close()
754 return DER_cert_to_PEM_cert(dercert)
755
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000756def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200757 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')