Skip to content

Commit c3ead98

Browse files
committed
Fix socketpair() on platforms without _socket.socketpair
Windows has no _socket.socketpair(), so socket.socketpair() falls back to a pure-Python implementation built on an AF_INET loopback pair. mocket replaced socket.socket and socket.socketpair, so that fallback either resolved to MocketSocket or raised AttributeError, and any asyncio event loop created inside Mocketizer() died before the test body ran. Build the pair from true_socket when the C function is missing, take the accepted descriptor through _accept() so it is not wrapped back into MocketSocket, and authenticate the peer the same way CPython's fallback does since the CVE-2024-3219 fix. socket.socket stays patched, so mocking is unchanged for everything except the loopback pair the event loop makes. Refs kiwicom/pytest-recording#212, kiwicom/pytest-recording#213.
1 parent 17812a9 commit c3ead98

2 files changed

Lines changed: 159 additions & 1 deletion

File tree

‎mocket/socket.py‎

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,69 @@ def mock_inet_pton(address_family: int, ip_string: str) -> bytes:
107107
return bytes("\x7f\x00\x00\x01", "utf-8")
108108

109109

110+
def _loopback_socketpair(
111+
family: int = socket.AF_INET,
112+
socktype: int = socket.SOCK_STREAM,
113+
proto: int = 0,
114+
) -> tuple[socket.socket, socket.socket]:
115+
"""Build a connected pair of real sockets over the IPv4/IPv6 loopback.
116+
117+
Windows has no ``_socket.socketpair()``; the standard library builds the
118+
pair in Python instead. That code path resolves the module-level ``socket``
119+
name, which Mocket has already swapped for :class:`MocketSocket`, so the
120+
pair is assembled here from ``true_socket`` to keep it out of the mock
121+
layer. Only the loopback connection used by the event loop ends up here.
122+
"""
123+
if family == socket.AF_INET:
124+
host = "127.0.0.1"
125+
elif family == socket.AF_INET6:
126+
host = "::1"
127+
else:
128+
raise ValueError(
129+
f"Only AF_INET and AF_INET6 address families are supported: {family}"
130+
)
131+
if socktype != socket.SOCK_STREAM:
132+
raise ValueError(f"Only SOCK_STREAM socket type is supported: {socktype}")
133+
if proto != 0:
134+
raise ValueError(f"Only protocol zero is supported: {proto}")
135+
136+
lsock = true_socket(family, socktype, proto)
137+
try:
138+
lsock.bind((host, 0))
139+
lsock.listen()
140+
addr, port = lsock.getsockname()[:2]
141+
csock = true_socket(family, socktype, proto)
142+
try:
143+
csock.setblocking(False)
144+
with contextlib.suppress(BlockingIOError, InterruptedError):
145+
csock.connect((addr, port))
146+
csock.setblocking(True)
147+
# accept() would wrap the descriptor back into MocketSocket.
148+
fd, _peer = lsock._accept()
149+
ssock = true_socket(family, socktype, proto, fileno=fd)
150+
except Exception:
151+
csock.close()
152+
raise
153+
finally:
154+
lsock.close()
155+
156+
# Same check CPython added in its fallback for CVE-2024-3219: the listener
157+
# is reachable from outside the process, so make sure the peer we accepted
158+
# is our own csock and not somebody else that connected first.
159+
try:
160+
if (
161+
ssock.getsockname() != csock.getpeername()
162+
or csock.getsockname() != ssock.getpeername()
163+
):
164+
raise ConnectionError("Unexpected peer connection")
165+
except Exception:
166+
ssock.close()
167+
csock.close()
168+
raise
169+
170+
return ssock, csock
171+
172+
110173
def mock_socketpair(
111174
*args: Any,
112175
**kwargs: Any,
@@ -125,7 +188,10 @@ def mock_socketpair(
125188
"""
126189
import _socket
127190

128-
return _socket.socketpair(*args, **kwargs)
191+
if hasattr(_socket, "socketpair"):
192+
return _socket.socketpair(*args, **kwargs)
193+
194+
return _loopback_socketpair(*args, **kwargs)
129195

130196

131197
class MocketSocket:

‎tests/test_socketpair.py‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import asyncio
2+
import socket
3+
4+
import pytest
5+
6+
from mocket import Mocketizer
7+
from mocket.socket import MocketSocket
8+
9+
10+
def test_socketpair_returns_a_real_connected_pair():
11+
"""socketpair() must keep working while Mocket is enabled.
12+
13+
On Windows there is no C-level socketpair(), and the standard library
14+
fallback resolves the module-level ``socket`` name, which Mocket has
15+
swapped for MocketSocket. The pair therefore has to be built from the real
16+
socket class.
17+
"""
18+
with Mocketizer():
19+
a, b = socket.socketpair()
20+
try:
21+
a.send(b"ping")
22+
assert b.recv(4) == b"ping"
23+
b.send(b"pong")
24+
assert a.recv(4) == b"pong"
25+
finally:
26+
a.close()
27+
b.close()
28+
29+
30+
def test_asyncio_event_loop_can_be_created():
31+
"""asyncio creates its self-pipe with socketpair() when a loop is built."""
32+
with Mocketizer():
33+
loop = asyncio.new_event_loop()
34+
try:
35+
assert loop is not None
36+
finally:
37+
loop.close()
38+
39+
40+
def test_socketpair_does_not_disable_the_mock_layer():
41+
"""The loopback pair must not leak past socketpair() into user sockets."""
42+
with Mocketizer():
43+
a, b = socket.socketpair()
44+
a.close()
45+
b.close()
46+
47+
assert socket.socket is MocketSocket
48+
assert not isinstance(a, MocketSocket)
49+
50+
51+
def test_mock_socketpair_without_the_c_function(monkeypatch):
52+
"""Force the pure-Python path so POSIX CI covers it too."""
53+
import _socket
54+
55+
monkeypatch.delattr(_socket, "socketpair", raising=False)
56+
57+
with Mocketizer():
58+
a, b = socket.socketpair()
59+
try:
60+
a.send(b"ping")
61+
assert b.recv(4) == b"ping"
62+
finally:
63+
a.close()
64+
b.close()
65+
66+
loop = asyncio.new_event_loop()
67+
loop.close()
68+
69+
70+
def test_loopback_socketpair_rejects_a_foreign_peer(monkeypatch):
71+
"""CVE-2024-3219: the listener is reachable, so the peer must be ours."""
72+
from mocket.socket import _loopback_socketpair
73+
74+
listener = socket.socket()
75+
listener.bind(("127.0.0.1", 0))
76+
listener.listen(1)
77+
attacker = socket.socket()
78+
attacker.connect(listener.getsockname())
79+
hijacked, _ = listener.accept()
80+
foreign_peer = hijacked.getpeername()
81+
hijacked_fd = hijacked.detach()
82+
83+
def fake_accept(self):
84+
return hijacked_fd, foreign_peer
85+
86+
monkeypatch.setattr(socket.socket, "_accept", fake_accept)
87+
try:
88+
with pytest.raises(ConnectionError, match="Unexpected peer connection"):
89+
_loopback_socketpair()
90+
finally:
91+
listener.close()
92+
attacker.close()

0 commit comments

Comments
 (0)