blob: d4c7bad6f804ea7b6bd5e57f8afe6d67ef33bbf0 [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
Christian Heimesa6bc95a2013-11-17 19:59:14 +010094from collections import namedtuple
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
Christian Heimes22587792013-11-21 23:56:13 +0100105from _ssl import (VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAIN,
106 VERIFY_X509_STRICT)
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100107from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinner99c8b162011-05-24 12:05:19 +0200108from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100109
110def _import_symbols(prefix):
111 for n in dir(_ssl):
112 if n.startswith(prefix):
113 globals()[n] = getattr(_ssl, n)
114
115_import_symbols('OP_')
116_import_symbols('ALERT_DESCRIPTION_')
117_import_symbols('SSL_ERROR_')
118
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100119from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100120
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100121from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200122from _ssl import _OPENSSL_API_VERSION
123
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100124
Victor Stinner3de49192011-05-09 00:42:58 +0200125_PROTOCOL_NAMES = {
126 PROTOCOL_TLSv1: "TLSv1",
127 PROTOCOL_SSLv23: "SSLv23",
128 PROTOCOL_SSLv3: "SSLv3",
129}
130try:
131 from _ssl import PROTOCOL_SSLv2
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100132 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Brett Cannoncd171c82013-07-04 17:43:24 -0400133except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100134 _SSLv2_IF_EXISTS = None
Victor Stinner3de49192011-05-09 00:42:58 +0200135else:
136 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +0000137
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100138try:
139 from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
Brett Cannoncd171c82013-07-04 17:43:24 -0400140except ImportError:
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100141 pass
142else:
143 _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1"
144 _PROTOCOL_NAMES[PROTOCOL_TLSv1_2] = "TLSv1.2"
145
Christian Heimes46bebee2013-06-09 19:03:31 +0200146if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100147 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200148
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000149from socket import getnameinfo as _getnameinfo
Antoine Pitrou15399c32011-04-28 19:23:55 +0200150from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000151import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +0000152import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000153import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000154
Andrew Svetlov0832af62012-12-18 23:10:48 +0200155
156socket_error = OSError # keep that public name in module namespace
157
Antoine Pitroud6494802011-07-21 01:11:30 +0200158if _ssl.HAS_TLS_UNIQUE:
159 CHANNEL_BINDING_TYPES = ['tls-unique']
160else:
161 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000162
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100163# Disable weak or insecure ciphers by default
164# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
165_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
166
Thomas Woutersed03b412007-08-28 21:37:11 +0000167
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000168class CertificateError(ValueError):
169 pass
170
171
Georg Brandl72c98d32013-10-27 07:16:53 +0100172def _dnsname_match(dn, hostname, max_wildcards=1):
173 """Matching according to RFC 6125, section 6.4.3
174
175 http://tools.ietf.org/html/rfc6125#section-6.4.3
176 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000177 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100178 if not dn:
179 return False
180
181 leftmost, *remainder = dn.split(r'.')
182
183 wildcards = leftmost.count('*')
184 if wildcards > max_wildcards:
185 # Issue #17980: avoid denials of service by refusing more
186 # than one wildcard per fragment. A survery of established
187 # policy among SSL implementations showed it to be a
188 # reasonable choice.
189 raise CertificateError(
190 "too many wildcards in certificate DNS name: " + repr(dn))
191
192 # speed up common case w/o wildcards
193 if not wildcards:
194 return dn.lower() == hostname.lower()
195
196 # RFC 6125, section 6.4.3, subitem 1.
197 # The client SHOULD NOT attempt to match a presented identifier in which
198 # the wildcard character comprises a label other than the left-most label.
199 if leftmost == '*':
200 # When '*' is a fragment by itself, it matches a non-empty dotless
201 # fragment.
202 pats.append('[^.]+')
203 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
204 # RFC 6125, section 6.4.3, subitem 3.
205 # The client SHOULD NOT attempt to match a presented identifier
206 # where the wildcard character is embedded within an A-label or
207 # U-label of an internationalized domain name.
208 pats.append(re.escape(leftmost))
209 else:
210 # Otherwise, '*' matches any dotless string, e.g. www*
211 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
212
213 # add the remaining fragments, ignore any wildcards
214 for frag in remainder:
215 pats.append(re.escape(frag))
216
217 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
218 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000219
220
221def match_hostname(cert, hostname):
222 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100223 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
224 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000225
226 CertificateError is raised on failure. On success, the function
227 returns nothing.
228 """
229 if not cert:
230 raise ValueError("empty or no certificate")
231 dnsnames = []
232 san = cert.get('subjectAltName', ())
233 for key, value in san:
234 if key == 'DNS':
Georg Brandl72c98d32013-10-27 07:16:53 +0100235 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000236 return
237 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200238 if not dnsnames:
239 # The subject is only checked when there is no dNSName entry
240 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000241 for sub in cert.get('subject', ()):
242 for key, value in sub:
243 # XXX according to RFC 2818, the most specific Common Name
244 # must be used.
245 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100246 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000247 return
248 dnsnames.append(value)
249 if len(dnsnames) > 1:
250 raise CertificateError("hostname %r "
251 "doesn't match either of %s"
252 % (hostname, ', '.join(map(repr, dnsnames))))
253 elif len(dnsnames) == 1:
254 raise CertificateError("hostname %r "
255 "doesn't match %r"
256 % (hostname, dnsnames[0]))
257 else:
258 raise CertificateError("no appropriate commonName or "
259 "subjectAltName fields were found")
260
261
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100262DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200263 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
264 "openssl_capath")
265
266def get_default_verify_paths():
267 """Return paths to default cafile and capath.
268 """
269 parts = _ssl.get_default_verify_paths()
270
271 # environment vars shadow paths
272 cafile = os.environ.get(parts[0], parts[1])
273 capath = os.environ.get(parts[2], parts[3])
274
275 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
276 capath if os.path.isdir(capath) else None,
277 *parts)
278
279
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100280class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
281 """ASN.1 object identifier lookup
282 """
283 __slots__ = ()
284
285 def __new__(cls, oid):
286 return super().__new__(cls, *_txt2obj(oid, name=False))
287
288 @classmethod
289 def fromnid(cls, nid):
290 """Create _ASN1Object from OpenSSL numeric ID
291 """
292 return super().__new__(cls, *_nid2obj(nid))
293
294 @classmethod
295 def fromname(cls, name):
296 """Create _ASN1Object from short name, long name or OID
297 """
298 return super().__new__(cls, *_txt2obj(name, name=True))
299
300
Antoine Pitrou152efa22010-05-16 18:19:27 +0000301class SSLContext(_SSLContext):
302 """An SSLContext holds various SSL-related configuration options and
303 data, such as certificates and possibly a private key."""
304
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100305 __slots__ = ('protocol', '__weakref__')
Antoine Pitrou152efa22010-05-16 18:19:27 +0000306
307 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100308 self = _SSLContext.__new__(cls, protocol)
309 if protocol != _SSLv2_IF_EXISTS:
310 self.set_ciphers(_DEFAULT_CIPHERS)
311 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000312
313 def __init__(self, protocol):
314 self.protocol = protocol
315
316 def wrap_socket(self, sock, server_side=False,
317 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000318 suppress_ragged_eofs=True,
319 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000320 return SSLSocket(sock=sock, server_side=server_side,
321 do_handshake_on_connect=do_handshake_on_connect,
322 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000323 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000324 _context=self)
325
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100326 def set_npn_protocols(self, npn_protocols):
327 protos = bytearray()
328 for protocol in npn_protocols:
329 b = bytes(protocol, 'ascii')
330 if len(b) == 0 or len(b) > 255:
331 raise SSLError('NPN protocols must be 1 to 255 in length')
332 protos.append(len(b))
333 protos.extend(b)
334
335 self._set_npn_protocols(protos)
336
Antoine Pitrou152efa22010-05-16 18:19:27 +0000337
338class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000339 """This class implements a subtype of socket.socket that wraps
340 the underlying OS socket in an SSL context when necessary, and
341 provides read and write methods over that channel."""
342
Bill Janssen6e027db2007-11-15 22:23:56 +0000343 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000344 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000345 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
346 do_handshake_on_connect=True,
347 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100348 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000349 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000350 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000351
Antoine Pitrou152efa22010-05-16 18:19:27 +0000352 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100353 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000354 else:
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000355 if server_side and not certfile:
356 raise ValueError("certfile must be specified for server-side "
357 "operations")
Giampaolo RodolĂ 8b7da622010-08-30 18:28:05 +0000358 if keyfile and not certfile:
359 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000360 if certfile and not keyfile:
361 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100362 self._context = SSLContext(ssl_version)
363 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000364 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100365 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000366 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100367 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100368 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100369 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000370 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100371 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000372 self.keyfile = keyfile
373 self.certfile = certfile
374 self.cert_reqs = cert_reqs
375 self.ssl_version = ssl_version
376 self.ca_certs = ca_certs
377 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000378 if server_side and server_hostname:
379 raise ValueError("server_hostname can only be specified "
380 "in client mode")
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000381 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000382 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000383 self.do_handshake_on_connect = do_handshake_on_connect
384 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000385 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000386 socket.__init__(self,
387 family=sock.family,
388 type=sock.type,
389 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000390 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000391 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000392 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000393 elif fileno is not None:
394 socket.__init__(self, fileno=fileno)
395 else:
396 socket.__init__(self, family=family, type=type, proto=proto)
397
Antoine Pitrou242db722013-05-01 20:52:07 +0200398 # See if we are connected
399 try:
400 self.getpeername()
401 except OSError as e:
402 if e.errno != errno.ENOTCONN:
403 raise
404 connected = False
405 else:
406 connected = True
407
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000408 self._closed = False
409 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000410 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000411 if connected:
412 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000413 try:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100414 self._sslobj = self._context._wrap_socket(self, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +0000415 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000416 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000417 timeout = self.gettimeout()
418 if timeout == 0.0:
419 # non-blocking
420 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000421 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000422
Andrew Svetlov0832af62012-12-18 23:10:48 +0200423 except OSError as x:
Bill Janssen6e027db2007-11-15 22:23:56 +0000424 self.close()
425 raise x
Antoine Pitrou242db722013-05-01 20:52:07 +0200426
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100427 @property
428 def context(self):
429 return self._context
430
431 @context.setter
432 def context(self, ctx):
433 self._context = ctx
434 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000435
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000436 def dup(self):
437 raise NotImplemented("Can't dup() %s instances" %
438 self.__class__.__name__)
439
Bill Janssen6e027db2007-11-15 22:23:56 +0000440 def _checkClosed(self, msg=None):
441 # raise an exception here if you wish to check for spurious closes
442 pass
443
Antoine Pitrou242db722013-05-01 20:52:07 +0200444 def _check_connected(self):
445 if not self._connected:
446 # getpeername() will raise ENOTCONN if the socket is really
447 # not connected; note that we can be connected even without
448 # _connected being set, e.g. if connect() first returned
449 # EAGAIN.
450 self.getpeername()
451
Bill Janssen54cc54c2007-12-14 22:08:56 +0000452 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000453 """Read up to LEN bytes and return them.
454 Return zero-length string on EOF."""
455
Bill Janssen6e027db2007-11-15 22:23:56 +0000456 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200457 if not self._sslobj:
458 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000459 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000460 if buffer is not None:
461 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000462 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000463 v = self._sslobj.read(len or 1024)
464 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000465 except SSLError as x:
466 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000467 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000468 return 0
469 else:
470 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000471 else:
472 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000473
474 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000475 """Write DATA to the underlying SSL channel. Returns
476 number of bytes of DATA actually transmitted."""
477
Bill Janssen6e027db2007-11-15 22:23:56 +0000478 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200479 if not self._sslobj:
480 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000481 return self._sslobj.write(data)
482
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000483 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000484 """Returns a formatted version of the data in the
485 certificate provided by the other end of the SSL channel.
486 Return None if no certificate was provided, {} if a
487 certificate was provided, but not validated."""
488
Bill Janssen6e027db2007-11-15 22:23:56 +0000489 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200490 self._check_connected()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000491 return self._sslobj.peer_certificate(binary_form)
492
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100493 def selected_npn_protocol(self):
494 self._checkClosed()
495 if not self._sslobj or not _ssl.HAS_NPN:
496 return None
497 else:
498 return self._sslobj.selected_npn_protocol()
499
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000500 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000501 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000502 if not self._sslobj:
503 return None
504 else:
505 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000506
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100507 def compression(self):
508 self._checkClosed()
509 if not self._sslobj:
510 return None
511 else:
512 return self._sslobj.compression()
513
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000514 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000515 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000516 if self._sslobj:
517 if flags != 0:
518 raise ValueError(
519 "non-zero flags not allowed in calls to send() on %s" %
520 self.__class__)
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200521 try:
522 v = self._sslobj.write(data)
523 except SSLError as x:
524 if x.args[0] == SSL_ERROR_WANT_READ:
525 return 0
526 elif x.args[0] == SSL_ERROR_WANT_WRITE:
527 return 0
Bill Janssen6e027db2007-11-15 22:23:56 +0000528 else:
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200529 raise
530 else:
531 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000532 else:
533 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000534
Antoine Pitroua468adc2010-09-14 14:43:44 +0000535 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000536 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000537 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000538 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000539 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000540 elif addr is None:
541 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000542 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000543 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000544
Nick Coghlan513886a2011-08-28 00:00:27 +1000545 def sendmsg(self, *args, **kwargs):
546 # Ensure programs don't send data unencrypted if they try to
547 # use this method.
548 raise NotImplementedError("sendmsg not allowed on instances of %s" %
549 self.__class__)
550
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000551 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000552 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000553 if self._sslobj:
Giampaolo RodolĂ 374f8352010-08-29 12:08:09 +0000554 if flags != 0:
555 raise ValueError(
556 "non-zero flags not allowed in calls to sendall() on %s" %
557 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000558 amount = len(data)
559 count = 0
560 while (count < amount):
561 v = self.send(data[count:])
562 count += v
563 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000564 else:
565 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000566
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000567 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000568 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000569 if self._sslobj:
570 if flags != 0:
571 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000572 "non-zero flags not allowed in calls to recv() on %s" %
573 self.__class__)
574 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000575 else:
576 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000577
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000578 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000579 self._checkClosed()
580 if buffer and (nbytes is None):
581 nbytes = len(buffer)
582 elif nbytes is None:
583 nbytes = 1024
584 if self._sslobj:
585 if flags != 0:
586 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000587 "non-zero flags not allowed in calls to recv_into() on %s" %
588 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000589 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000590 else:
591 return socket.recv_into(self, buffer, nbytes, flags)
592
Antoine Pitroua468adc2010-09-14 14:43:44 +0000593 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000594 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000595 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000596 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000597 self.__class__)
598 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000599 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000600
Bill Janssen58afe4c2008-09-08 16:45:19 +0000601 def recvfrom_into(self, buffer, nbytes=None, flags=0):
602 self._checkClosed()
603 if self._sslobj:
604 raise ValueError("recvfrom_into not allowed on instances of %s" %
605 self.__class__)
606 else:
607 return socket.recvfrom_into(self, buffer, nbytes, flags)
608
Nick Coghlan513886a2011-08-28 00:00:27 +1000609 def recvmsg(self, *args, **kwargs):
610 raise NotImplementedError("recvmsg not allowed on instances of %s" %
611 self.__class__)
612
613 def recvmsg_into(self, *args, **kwargs):
614 raise NotImplementedError("recvmsg_into not allowed on instances of "
615 "%s" % self.__class__)
616
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000617 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000618 self._checkClosed()
619 if self._sslobj:
620 return self._sslobj.pending()
621 else:
622 return 0
623
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000624 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000625 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000627 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000628
Ezio Melottidc55e672010-01-18 09:15:14 +0000629 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000630 if self._sslobj:
631 s = self._sslobj.shutdown()
632 self._sslobj = None
633 return s
634 else:
635 raise ValueError("No SSL wrapper around " + str(self))
636
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000637 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000638 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000639 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000640
Bill Janssen48dc27c2007-12-05 03:38:10 +0000641 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000642 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200643 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000644 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000645 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000646 if timeout == 0.0 and block:
647 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000648 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000649 finally:
650 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000651
Antoine Pitroub4410db2011-05-18 18:51:06 +0200652 def _real_connect(self, addr, connect_ex):
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000653 if self.server_side:
654 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000655 # Here we assume that the socket is client-side, and not
656 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000657 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000659 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000660 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200661 if connect_ex:
662 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000663 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200664 rc = None
665 socket.connect(self, addr)
666 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +0200667 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +0200668 if self.do_handshake_on_connect:
669 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +0200670 return rc
Andrew Svetlov0832af62012-12-18 23:10:48 +0200671 except OSError:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200672 self._sslobj = None
673 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000674
675 def connect(self, addr):
676 """Connects to remote ADDR, and then wraps the connection in
677 an SSL channel."""
678 self._real_connect(addr, False)
679
680 def connect_ex(self, addr):
681 """Connects to remote ADDR, and then wraps the connection in
682 an SSL channel."""
683 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000684
685 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000686 """Accepts a new connection from a remote client, and returns
687 a tuple containing that new connection wrapped with a server-side
688 SSL channel, and the address of the remote client."""
689
690 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100691 newsock = self.context.wrap_socket(newsock,
692 do_handshake_on_connect=self.do_handshake_on_connect,
693 suppress_ragged_eofs=self.suppress_ragged_eofs,
694 server_side=True)
695 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000696
Antoine Pitroud6494802011-07-21 01:11:30 +0200697 def get_channel_binding(self, cb_type="tls-unique"):
698 """Get channel binding data for current connection. Raise ValueError
699 if the requested `cb_type` is not supported. Return bytes of the data
700 or None if the data is not available (e.g. before the handshake).
701 """
702 if cb_type not in CHANNEL_BINDING_TYPES:
703 raise ValueError("Unsupported channel binding type")
704 if cb_type != "tls-unique":
705 raise NotImplementedError(
706 "{0} channel binding type not implemented"
707 .format(cb_type))
708 if self._sslobj is None:
709 return None
710 return self._sslobj.tls_unique_cb()
711
Bill Janssen54cc54c2007-12-14 22:08:56 +0000712
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000713def wrap_socket(sock, keyfile=None, certfile=None,
714 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000715 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000716 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100717 suppress_ragged_eofs=True,
718 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000719
Bill Janssen6e027db2007-11-15 22:23:56 +0000720 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000721 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000722 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000723 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000724 suppress_ragged_eofs=suppress_ragged_eofs,
725 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726
Thomas Woutersed03b412007-08-28 21:37:11 +0000727# some utility functions
728
729def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000730 """Takes a date-time string in standard ASN1_print form
731 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
732 a Python time value in seconds past the epoch."""
733
Thomas Woutersed03b412007-08-28 21:37:11 +0000734 import time
735 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
736
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737PEM_HEADER = "-----BEGIN CERTIFICATE-----"
738PEM_FOOTER = "-----END CERTIFICATE-----"
739
740def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000741 """Takes a certificate in binary DER format and returns the
742 PEM version of it as a string."""
743
Bill Janssen6e027db2007-11-15 22:23:56 +0000744 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
745 return (PEM_HEADER + '\n' +
746 textwrap.fill(f, 64) + '\n' +
747 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000748
749def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000750 """Takes a certificate in ASCII PEM format and returns the
751 DER-encoded version of it as a byte sequence"""
752
753 if not pem_cert_string.startswith(PEM_HEADER):
754 raise ValueError("Invalid PEM encoding; must start with %s"
755 % PEM_HEADER)
756 if not pem_cert_string.strip().endswith(PEM_FOOTER):
757 raise ValueError("Invalid PEM encoding; must end with %s"
758 % PEM_FOOTER)
759 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000760 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000761
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000762def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000763 """Retrieve the certificate from the server at the specified address,
764 and return it as a PEM-encoded string.
765 If 'ca_certs' is specified, validate the server cert against it.
766 If 'ssl_version' is specified, use it in the connection attempt."""
767
768 host, port = addr
769 if (ca_certs is not None):
770 cert_reqs = CERT_REQUIRED
771 else:
772 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200773 s = create_connection(addr)
774 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000775 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000776 dercert = s.getpeercert(True)
777 s.close()
778 return DER_cert_to_PEM_cert(dercert)
779
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000780def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200781 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')