Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions Lib/ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,10 @@ def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
self = _SSLContext.__new__(cls, protocol)
return self

def __getstate__(self):
raise TypeError("cannot serialize {} object".format(
self.__class__.__name__))

def _encode_hostname(self, hostname):
if hostname is None:
return None
Expand Down Expand Up @@ -695,6 +699,10 @@ def server_hostname(self):
server hostame is set."""
return self._sslobj.server_hostname

def __getstate__(self):
raise TypeError("cannot serialize {} object".format(
self.__class__.__name__))

def read(self, len=1024, buffer=None):
"""Read up to 'len' bytes from the SSL object and return them.

Expand Down Expand Up @@ -880,9 +888,13 @@ def session_reused(self):
if self._sslobj is not None:
return self._sslobj.session_reused

def __getstate__(self):
raise TypeError("cannot serialize {} object".format(
self.__class__.__name__))

def dup(self):
raise NotImplemented("Can't dup() %s instances" %
self.__class__.__name__)
raise NotImplementedError("Can't dup() {} instances".format(
self.__class__.__name__))

def _checkClosed(self, msg=None):
# raise an exception here if you wish to check for spurious closes
Expand Down
22 changes: 22 additions & 0 deletions Lib/test/test_ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import platform
import functools
import sysconfig
import copy
import pickle
try:
import ctypes
except ImportError:
Expand Down Expand Up @@ -972,6 +974,17 @@ def test_connect_ex_error(self):
)
self.assertIn(rc, errors)

def test_copy_pickle(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
with ctx.wrap_socket(socket.socket(),
server_hostname='localhost') as s:
with self.assertRaises(TypeError):
copy.copy(s)
with self.assertRaises(TypeError):
copy.deepcopy(s)
with self.assertRaises(TypeError):
pickle.dumps(s)


class ContextTests(unittest.TestCase):

Expand Down Expand Up @@ -1608,6 +1621,15 @@ class MySSLObject(ssl.SSLObject):
obj = ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO())
self.assertIsInstance(obj, MySSLObject)

def test_copy_pickle(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
with self.assertRaises(TypeError):
copy.copy(ctx)
with self.assertRaises(TypeError):
copy.deepcopy(ctx)
with self.assertRaises(TypeError):
pickle.dumps(ctx)


class SSLErrorTests(unittest.TestCase):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Improve error message when trying to serialize SSLContext, SSLObject, and
SSLSocket objects. The classes can't be pickled or copied by the copy
module.