Skip to content

Commit 373984a

Browse files
committed
Fix the foreign-peer test on Linux: accept the real connection first
_loopback_socketpair() connects with setblocking(False) -- the same trick CPython's own fallback uses -- and counts on the accept() that follows to wait for the handshake, because only then is getpeername() meaningful. The hijacked _accept() here returned a foreign peer without waiting, so on Linux csock was still in SYN_SENT when the CVE check called getpeername() and the test failed with ENOTCONN instead of the ConnectionError it is about. Windows connects to the loopback synchronously and never showed it. Drain the real connection inside the hijack, then close it. Signed-off-by: Simin Yuan <281164480+simin-yuan@users.noreply.github.com>
1 parent 49f8b59 commit 373984a

1 file changed

Lines changed: 14 additions & 0 deletions

File tree

‎tests/test_socketpair.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,20 @@ def test_loopback_socketpair_rejects_a_foreign_peer(monkeypatch):
9191

9292
class HijackedListener(real):
9393
def _accept(self):
94+
# _loopback_socketpair() connects with setblocking(False), exactly
95+
# like CPython's own fallback, and relies on accept() to wait for
96+
# the handshake before the peer check calls getpeername(). Linux
97+
# leaves that connect in SYN_SENT for a moment, so skipping the
98+
# wait here makes getpeername() raise ENOTCONN instead of the
99+
# ConnectionError this test is about. Drain the real connection
100+
# first; its peer is nobody we care about.
101+
# Socket._accept() is CPython-internal and missing from the type
102+
# stubs, hence the ignore: it is the only way to bypass the
103+
# override above without recursing through accept().
104+
real_fd, _ = real._accept(self) # type: ignore[attr-defined]
105+
# Wrap it before closing: on Windows a socket descriptor is not
106+
# an OS file descriptor, so os.close() would raise EBADF.
107+
real(fileno=real_fd).close()
94108
return hijacked_fd, foreign_peer
95109

96110
monkeypatch.setattr(mocket_socket_module, "true_socket", HijackedListener)

0 commit comments

Comments
 (0)