Skip to content

Commit 49f8b59

Browse files
committed
Fix foreign-peer test under gevent socket patching
tests/test_http_gevent.py patches socket at import time, so the hijack has to be installed on mocket.socket.true_socket. Signed-off-by: Simin Yuan <281164480+simin-yuan@users.noreply.github.com>
1 parent c3ead98 commit 49f8b59

1 file changed

Lines changed: 18 additions & 8 deletions

File tree

‎tests/test_socketpair.py‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -68,22 +68,32 @@ def test_mock_socketpair_without_the_c_function(monkeypatch):
6868

6969

7070
def test_loopback_socketpair_rejects_a_foreign_peer(monkeypatch):
71-
"""CVE-2024-3219: the listener is reachable, so the peer must be ours."""
71+
"""CVE-2024-3219: the listener is reachable, so the peer must be ours.
72+
73+
The hijack has to be installed on ``mocket.socket.true_socket``, which is
74+
the name ``_loopback_socketpair`` resolves. Patching ``socket.socket``
75+
instead only works while that name still points at the same class: the
76+
gevent tests in this suite call ``monkey.patch_socket()`` at import time,
77+
which leaves ``socket.socket`` bound to gevent's subclass while
78+
``true_socket`` keeps the original one, so the hijack silently missed.
79+
"""
80+
from mocket import socket as mocket_socket_module
7281
from mocket.socket import _loopback_socketpair
7382

74-
listener = socket.socket()
83+
real = mocket_socket_module.true_socket
84+
listener = real(socket.AF_INET, socket.SOCK_STREAM)
7585
listener.bind(("127.0.0.1", 0))
7686
listener.listen(1)
77-
attacker = socket.socket()
87+
attacker = real(socket.AF_INET, socket.SOCK_STREAM)
7888
attacker.connect(listener.getsockname())
79-
hijacked, _ = listener.accept()
80-
foreign_peer = hijacked.getpeername()
89+
hijacked, foreign_peer = listener.accept()
8190
hijacked_fd = hijacked.detach()
8291

83-
def fake_accept(self):
84-
return hijacked_fd, foreign_peer
92+
class HijackedListener(real):
93+
def _accept(self):
94+
return hijacked_fd, foreign_peer
8595

86-
monkeypatch.setattr(socket.socket, "_accept", fake_accept)
96+
monkeypatch.setattr(mocket_socket_module, "true_socket", HijackedListener)
8797
try:
8898
with pytest.raises(ConnectionError, match="Unexpected peer connection"):
8999
_loopback_socketpair()

0 commit comments

Comments
 (0)