Merge bitcoin/bitcoin#36916: test: avoid BSD ephemeral-port collisions in HTTP clients
What changed, and why it matters
This commit fixes a flaky-test problem on FreeBSD and OpenBSD, not a security vulnerability in the Bitcoin Core software users run. The test framework sometimes randomly picked a network source port that collided with a port used by the tests themselves. In rare cases a test HTTP client could accidentally connect to itself, causing confusing test failures. The fix makes Python's built-in HTTP client use the same port-range workaround already used for other test sockets. It only affects the automated test suite and only on BSD operating systems.
No production action needed. Test-only reliability improvement; ensure CI includes the new netutil unit test on FreeBSD/OpenBSD runners if available.
Security signals we found
Fixes self-connect scenario in test HTTP clients on BSD
Prevents source-port collision between test client and test listener ports
Only affects test framework, not production node networking
No change to consensus, P2P, wallet, or RPC server code
Evidence from the diff
The patch adds a test_framework.netutil.HTTPConnection subclass of http.client.HTTPConnection whose _create_connection uses a helper that calls set_ephemeral_port_range() before connect(). This keeps ephemeral source ports in the high BSD range (IP_PORTRANGE_HIGH/IPV6_PORTRANGE_HIGH) and outside the test framework’s static port range. It updates AuthServiceProxy and several functional tests to use the new class. Unit tests verify the socket option is set before connect() on freebsd/openbsd.
Changed components
test/functional/test_framework/netutil.pytest/functional/test_framework/authproxy.pytest/functional/feature_io_errors.pytest/functional/interface_http.pytest/functional/interface_rest.pytest/functional/rpc_users.pytest/functional/rpc_whitelist.pytest/functional/feature_framework_unit_tests.pyInspect captured patch +67 / −12
### test/functional/feature_framework_unit_tests.py
@@ -25,6 +25,7 @@
"extendedkey",
"key",
"messages",
+ "netutil",
"crypto.muhash",
"crypto.poly1305",
"crypto.ripemd160",
### test/functional/feature_io_errors.py
@@ -5,9 +5,9 @@
"""Test handling of I/O errors."""
from contextlib import closing
-import http.client
import urllib.parse
+from test_framework.netutil import HTTPConnection
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
@@ -45,7 +45,7 @@ def test_blk_dat_io_error(self):
self.log.info("Check REST /tx/ on I/O errors")
url = urllib.parse.urlparse(node.url)
- with closing(http.client.HTTPConnection(url.hostname, url.port)) as conn:
+ with closing(HTTPConnection(url.hostname, url.port)) as conn:
conn.request("GET", f"/rest/tx/{txid}.json")
response = conn.getresponse()
assert_equal(response.status, 500)
### test/functional/interface_http.py
@@ -5,7 +5,7 @@
"""Test the HTTP server basics."""
from test_framework.test_framework import BitcoinTestFramework
-from test_framework.netutil import NETWORK_ERRORS
+from test_framework.netutil import HTTPConnection, NETWORK_ERRORS
from test_framework.util import (
assert_equal,
assert_raises,
@@ -38,7 +38,7 @@ def __init__(self, node):
self.reset_conn()
def reset_conn(self):
- self.conn = http.client.HTTPConnection(self.url.hostname, self.url.port, timeout=self.timeout)
+ self.conn = HTTPConnection(self.url.hostname, self.url.port, timeout=self.timeout)
self.conn.connect()
def sock_closed(self):
### test/functional/interface_rest.py
@@ -18,6 +18,7 @@
COIN,
deser_block_spent_outputs,
)
+from test_framework.netutil import HTTPConnection
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
@@ -76,7 +77,7 @@ def test_rest_request(
else:
rest_uri += f'?{urllib.parse.urlencode(query_params)}'
- conn = http.client.HTTPConnection(self.url.hostname, self.url.port, timeout=self.rpc_timeout)
+ conn = HTTPConnection(self.url.hostname, self.url.port, timeout=self.rpc_timeout)
self.log.debug(f'{http_method} {rest_uri} {body}')
if http_method == 'GET':
conn.request('GET', rest_uri)
### test/functional/rpc_users.py
@@ -4,13 +4,13 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test multiple RPC users."""
+from test_framework.netutil import HTTPConnection
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
str_to_b64str,
)
-import http.client
import os
import platform
import urllib.parse
@@ -25,7 +25,7 @@ def call_with_auth(node, user, password, method="getbestblockhash"):
url = urllib.parse.urlparse(node.url)
headers = {"Authorization": "Basic " + str_to_b64str('{}:{}'.format(user, password))}
- conn = http.client.HTTPConnection(url.hostname, url.port, timeout=node.rpc_timeout)
+ conn = HTTPConnection(url.hostname, url.port, timeout=node.rpc_timeout)
conn.connect()
conn.request('POST', '/', f'{{"method": "{method}"}}', headers)
resp = conn.getresponse()
### test/functional/rpc_whitelist.py
@@ -5,12 +5,12 @@
"""
A test for RPC users with restricted permissions
"""
+from test_framework.netutil import HTTPConnection
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
str_to_b64str,
)
-import http.client
import json
import urllib.parse
@@ -19,7 +19,7 @@ def rpccall(node, user, method, *, batch=False):
url = urllib.parse.urlparse(node.url)
headers = {"Authorization": "Basic " + str_to_b64str('{}:{}'.format(user[0], user[3]))}
request = {"method": method}
- conn = http.client.HTTPConnection(url.hostname, url.port, timeout=node.rpc_timeout)
+ conn = HTTPConnection(url.hostname, url.port, timeout=node.rpc_timeout)
conn.connect()
conn.request('POST', '/', json.dumps([request] if batch else request), headers)
resp = conn.getresponse()
### test/functional/test_framework/authproxy.py
@@ -44,6 +44,7 @@
import time
import urllib.parse
+from .netutil import HTTPConnection
from .util import JSONRPCException, assert_equal
HTTP_TIMEOUT = 30
@@ -214,4 +215,4 @@ def _set_conn(self, connection=None):
elif self.__url.scheme == 'https':
self.__conn = http.client.HTTPSConnection(self.__url.hostname, port, timeout=self.timeout)
else:
- self.__conn = http.client.HTTPConnection(self.__url.hostname, port, timeout=self.timeout)
+ self.__conn = HTTPConnection(self.__url.hostname, port, timeout=self.timeout)
### test/functional/test_framework/netutil.py
@@ -14,6 +14,8 @@
import struct
import array
import os
+import unittest
+from unittest.mock import Mock, patch
# Easily unreachable address. Attempts to connect to it will stay within the machine.
# Used to avoid non-loopback traffic or DNS queries.
@@ -241,8 +243,8 @@ def set_ephemeral_port_range(sock):
The default ephemeral port ranges on FreeBSD (10000-65535) and
OpenBSD (1024-49151) overlap with the test framework's static port
range starting at TEST_RUNNER_PORT_MIN (default=11000).
- Using IP_PORTRANGE_HIGH avoids this overlap when binding to port 0 for dynamic
- port allocation.
+ Using IP_PORTRANGE_HIGH avoids this overlap when binding to port 0 or
+ connecting without an explicit source port.
'''
if sys.platform.startswith(("freebsd", "openbsd")):
# Constants from FreeBSD/OpenBSD's netinet/in.h and netinet6/in6.h
@@ -253,3 +255,53 @@ def set_ephemeral_port_range(sock):
sock.setsockopt(socket.IPPROTO_IPV6, IPV6_PORTRANGE, IP_PORTRANGE_HIGH)
else:
sock.setsockopt(socket.IPPROTO_IP, IP_PORTRANGE, IP_PORTRANGE_HIGH)
+
+
+def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
+ """Like socket.create_connection(), but keep BSD source ports out of the test range."""
+ host, port = address
+ last_error = None
+ for family, socktype, proto, _, sockaddr in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
+ sock = None
+ try:
+ sock = socket.socket(family, socktype, proto)
+ set_ephemeral_port_range(sock)
+ if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
+ sock.settimeout(timeout)
+ if source_address:
+ sock.bind(source_address)
+ sock.connect(sockaddr)
+ return sock
+ except OSError as e:
+ last_error = e
+ if sock is not None:
+ sock.close()
+ if last_error is not None:
+ raise last_error
+ raise OSError("getaddrinfo returns an empty list")
+
+
+class HTTPConnection(http.client.HTTPConnection):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._create_connection = _create_connection
+
+
+class TestHTTPConnection(unittest.TestCase):
+ def test_bsd_port_range_before_connect(self):
+ for platform in ("freebsd15", "openbsd7"):
+ for family, sockaddr, option in (
+ (socket.AF_INET, ("127.0.0.1", 16072), (socket.IPPROTO_IP, 19, 1)),
+ (socket.AF_INET6, ("::1", 16072, 0, 0), (socket.IPPROTO_IPV6, 14, 1)),
+ ):
+ with self.subTest(platform=platform, family=family):
+ sock = Mock(family=family)
+ # The option must be set before the kernel picks a source port.
+ sock.connect.side_effect = lambda _: sock.setsockopt.assert_any_call(*option)
+ with patch.object(sys, "platform", platform), \
+ patch.object(socket, "getaddrinfo", return_value=[(family, socket.SOCK_STREAM, 0, "", sockaddr)]), \
+ patch.object(socket, "socket", return_value=sock):
+ conn = HTTPConnection("localhost", 16072, timeout=3)
+ conn.connect()
+ sock.connect.assert_called_once_with(sockaddr)
+ sock.settimeout.assert_called_once_with(3)Why this scored 19/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.