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
18 changes: 18 additions & 0 deletions pymysql/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,10 @@ def set_character_set(self, charset, collation=None):

def connect(self, sock=None):
self._closed = False
# A reconnect (e.g. ping(reconnect=True)) must not inherit the security
# state of a previous transport; it is set again once TLS or a unix
# socket is actually established below.
self._secure = False
try:
if sock is None:
if self.unix_socket:
Expand Down Expand Up @@ -1112,6 +1116,7 @@ def _process_auth(self, plugin_name, auth_packet, handler=None):
)
elif plugin_name == b"mysql_clear_password":
# https://dev.mysql.com/doc/internals/en/clear-text-authentication.html
self._check_cleartext_password_allowed(plugin_name)
data = self.password + b"\0"
elif plugin_name == b"dialog":
pkt = auth_packet
Expand All @@ -1122,6 +1127,7 @@ def _process_auth(self, plugin_name, auth_packet, handler=None):
prompt = pkt.read_all()

if prompt == b"Password: ":
self._check_cleartext_password_allowed(plugin_name)
self.write_packet(self.password + b"\0")
elif handler:
resp = "no response - TypeError within plugin.prompt method"
Expand Down Expand Up @@ -1161,6 +1167,18 @@ def _process_auth(self, plugin_name, auth_packet, handler=None):
pkt.check_error()
return pkt

def _check_cleartext_password_allowed(self, plugin_name):
# mysql_clear_password and the dialog plugin's password prompt send the
# password as-is. The server picks the plugin during the handshake, so a
# rogue server or a man-in-the-middle could ask for either one and read
# the password off the wire. Only answer over TLS or a unix socket.
if not self._secure:
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
raise err.OperationalError(
CR.CR_AUTH_PLUGIN_ERR,
f"Authentication plugin '{plugin_name.decode()}' sends the password"
" in clear text and requires a secure connection (TLS or unix socket)",
)

def _get_auth_plugin_handler(self, plugin_name):
plugin_class = self._auth_plugin_map.get(plugin_name)
if not plugin_class and isinstance(plugin_name, bytes):
Expand Down
59 changes: 59 additions & 0 deletions pymysql/tests/test_auth_state_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,65 @@ def test_authentication_packet_transitions(
expected_auth_responses
)

@pytest.mark.parametrize(
"switch_request",
[b"\xfemysql_clear_password\0", b"\xfedialog\0\x04Password: "],
ids=["mysql_clear_password", "dialog"],
)
def test_cleartext_password_is_refused_on_insecure_connection(self, switch_request):
"""A rogue server must not be able to read the password off a plain TCP link."""
conn = self.connection()
conn._secure = False

packets = [self.packet(switch_request), self.packet(self.ok_packet)]
with (
mock.patch.object(conn, "write_packet") as write_packet,
mock.patch.object(conn, "_read_packet", side_effect=packets),
pytest.raises(pymysql.err.OperationalError, match="secure connection"),
):
conn._request_authentication()

# Only the handshake response was written; the password never left the client.
assert len(write_packet.call_args_list) == 1

@pytest.mark.parametrize(
"switch_request",
[b"\xfemysql_clear_password\0", b"\xfedialog\0\x04Password: "],
ids=["mysql_clear_password", "dialog"],
)
def test_cleartext_password_is_sent_on_secure_connection(self, switch_request):
"""Over TLS or a unix socket the clear-text plugins keep working."""
conn = self.connection()

packets = [self.packet(switch_request), self.packet(self.ok_packet)]
with (
mock.patch.object(conn, "write_packet") as write_packet,
mock.patch.object(conn, "_read_packet", side_effect=packets),
):
conn._request_authentication()

assert [call.args[0] for call in write_packet.call_args_list[1:]] == [
self.password + b"\0"
]

def test_reconnect_does_not_inherit_secure_state(self):
"""A reconnect after TLS must not reuse the stale _secure flag."""
conn = self.connection()
assert conn._secure is True

switch_request = self.packet(b"\xfemysql_clear_password\0")
with (
mock.patch("socket.create_connection", return_value=mock.MagicMock()),
mock.patch.object(conn, "_get_server_information"),
mock.patch.object(conn, "write_packet") as write_packet,
mock.patch.object(conn, "_read_packet", return_value=switch_request),
pytest.raises(pymysql.err.OperationalError, match="secure connection"),
):
conn.connect()

assert conn._secure is False
assert len(write_packet.call_args_list) == 1

def test_multiple_auth_switch_requests_are_rejected(self):
"""Only one authentication-method switch is valid per handshake."""
conn = self.connection()
Expand Down