Skip to content

Commit 098a404

Browse files
committed
Allow passing a custom SSLContext for the connection instead of a dictionary
1 parent 1ab78d8 commit 098a404

1 file changed

Lines changed: 17 additions & 17 deletions

File tree

pymysql/connections.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -568,20 +568,13 @@ def __init__(self, host="localhost", user=None, password="",
568568
if local_infile:
569569
client_flag |= CLIENT.LOCAL_FILES
570570

571-
if ssl and ('capath' in ssl or 'cipher' in ssl):
572-
raise NotImplementedError('ssl options capath and cipher are not supported')
573-
574571
self.ssl = False
575572
if ssl:
576573
if not SSL_ENABLED:
577574
raise NotImplementedError("ssl module not found")
578575
self.ssl = True
579576
client_flag |= CLIENT.SSL
580-
for k in ('key', 'cert', 'ca'):
581-
v = None
582-
if k in ssl:
583-
v = ssl[k]
584-
setattr(self, k, v)
577+
self.ctx = self._create_ssl_ctx(ssl)
585578

586579
if read_default_group and not read_default_file:
587580
if sys.platform.startswith("win"):
@@ -655,6 +648,21 @@ def _config(key, arg):
655648
self.socket = None
656649
else:
657650
self.connect()
651+
652+
def _create_ssl_ctx(self,sslp):
653+
if isinstance(sslp,ssl.SSLContext):
654+
return sslp
655+
if ('capath' in sslp or 'cipher' in sslp):
656+
raise NotImplementedError('ssl options capath and cipher are not supported')
657+
ca = sslp.get('ca')
658+
ctx = ssl.create_default_context(cafile=ca)
659+
ctx.check_hostname = False
660+
ctx.verify_mode = ssl.CERT_NONE if ca is None else ssl.CERT_REQUIRED
661+
if 'cert' in sslp:
662+
ctx.load_cert_chain(sslp['cert'], keyfile=sslp.get('key'))
663+
ctx.options |= ssl.OP_NO_SSLv2
664+
ctx.options |= ssl.OP_NO_SSLv3
665+
return ctx
658666

659667
def close(self):
660668
"""Send the quit message and close the socket"""
@@ -1009,15 +1017,7 @@ def _request_authentication(self):
10091017
if DEBUG: dump_packet(data)
10101018
self._write_bytes(data)
10111019

1012-
ctx = ssl.create_default_context(cafile=self.ca)
1013-
ctx.check_hostname = False
1014-
ctx.verify_mode = ssl.CERT_NONE if self.ca is None else ssl.CERT_REQUIRED
1015-
if self.cert is not None:
1016-
ctx.load_cert_chain(self.cert, keyfile=self.key)
1017-
ctx.options |= ssl.OP_NO_SSLv2
1018-
ctx.options |= ssl.OP_NO_SSLv3
1019-
1020-
self.socket = ctx.wrap_socket(self.socket)
1020+
self.socket = self.ctx.wrap_socket(self.socket,server_hostname=self.host)
10211021
self._rfile = _makefile(self.socket, 'rb')
10221022

10231023
data = data_init + self.user + b'\0' + \

0 commit comments

Comments
 (0)