Skip to content

Commit 842e2a9

Browse files
committed
Merge bitcoin#20234: net: don't bind on 0.0.0.0 if binds are restricted to Tor
2feec3c net: don't bind on 0.0.0.0 if binds are restricted to Tor (Vasil Dimov) Pull request description: The semantic of `-bind` is to restrict the binding only to some address. If not specified, then the user does not care and we bind to `0.0.0.0`. If specified then we should honor the restriction and bind only to the specified address. Before this change, if no `-bind` is given then we would bind to `0.0.0.0:8333` and to `127.0.0.1:8334` (incoming Tor) which is ok - the user does not care to restrict the binding. However, if only `-bind=addr:port=onion` is given (without ordinary `-bind=`) then we would bind to `addr:port` _and_ to `0.0.0.0:8333` in addition. Change the above to not do the additional bind: if only `-bind=addr:port=onion` is given (without ordinary `-bind=`) then bind to `addr:port` (only) and consider incoming connections to that as Tor and do not advertise it. I.e. a Tor-only node. ACKs for top commit: laanwj: Code review ACK 2feec3c jonatack: utACK 2feec3c per `git diff a004833 2feec3c` hebasto: ACK 2feec3c, tested on Linux Mint 20.1 (x86_64): Tree-SHA512: a04483af601706da928958b92dc560f9cfcc78ab0bb9d74414636eed1c6f29ed538ce1fb5a17d41ed82c9c9a45ca94899d0966e7ef93da809c9bcdcdb1d1f040
2 parents e0fe658 + 2feec3c commit 842e2a9

File tree

5 files changed

+129
-29
lines changed

5 files changed

+129
-29
lines changed

src/init.cpp

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1717,25 +1717,34 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
17171717
return InitError(ResolveErrMsg("bind", bind_arg));
17181718
}
17191719

1720-
if (connOptions.onion_binds.empty()) {
1721-
connOptions.onion_binds.push_back(DefaultOnionServiceTarget());
1722-
}
1723-
1724-
if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
1725-
const auto bind_addr = connOptions.onion_binds.front();
1726-
if (connOptions.onion_binds.size() > 1) {
1727-
InitWarning(strprintf(_("More than one onion bind address is provided. Using %s for the automatically created Tor onion service."), bind_addr.ToStringIPPort()));
1728-
}
1729-
StartTorControl(bind_addr);
1730-
}
1731-
17321720
for (const std::string& strBind : args.GetArgs("-whitebind")) {
17331721
NetWhitebindPermissions whitebind;
17341722
bilingual_str error;
17351723
if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) return InitError(error);
17361724
connOptions.vWhiteBinds.push_back(whitebind);
17371725
}
17381726

1727+
// If the user did not specify -bind= or -whitebind= then we bind
1728+
// on any address - 0.0.0.0 (IPv4) and :: (IPv6).
1729+
connOptions.bind_on_any = args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
1730+
1731+
CService onion_service_target;
1732+
if (!connOptions.onion_binds.empty()) {
1733+
onion_service_target = connOptions.onion_binds.front();
1734+
} else {
1735+
onion_service_target = DefaultOnionServiceTarget();
1736+
connOptions.onion_binds.push_back(onion_service_target);
1737+
}
1738+
1739+
if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
1740+
if (connOptions.onion_binds.size() > 1) {
1741+
InitWarning(strprintf(_("More than one onion bind address is provided. Using %s "
1742+
"for the automatically created Tor onion service."),
1743+
onion_service_target.ToStringIPPort()));
1744+
}
1745+
StartTorControl(onion_service_target);
1746+
}
1747+
17391748
for (const auto& net : args.GetArgs("-whitelist")) {
17401749
NetWhitelistPermissions subnet;
17411750
bilingual_str error;

src/net.cpp

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2465,38 +2465,33 @@ bool CConnman::Bind(const CService &addr, unsigned int flags, NetPermissionFlags
24652465
return true;
24662466
}
24672467

2468-
bool CConnman::InitBinds(
2469-
const std::vector<CService>& binds,
2470-
const std::vector<NetWhitebindPermissions>& whiteBinds,
2471-
const std::vector<CService>& onion_binds)
2468+
bool CConnman::InitBinds(const Options& options)
24722469
{
24732470
bool fBound = false;
2474-
for (const auto& addrBind : binds) {
2471+
for (const auto& addrBind : options.vBinds) {
24752472
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR), NetPermissionFlags::None);
24762473
}
2477-
for (const auto& addrBind : whiteBinds) {
2474+
for (const auto& addrBind : options.vWhiteBinds) {
24782475
fBound |= Bind(addrBind.m_service, (BF_EXPLICIT | BF_REPORT_ERROR), addrBind.m_flags);
24792476
}
2480-
if (binds.empty() && whiteBinds.empty()) {
2477+
for (const auto& addr_bind : options.onion_binds) {
2478+
fBound |= Bind(addr_bind, BF_EXPLICIT | BF_DONT_ADVERTISE, NetPermissionFlags::None);
2479+
}
2480+
if (options.bind_on_any) {
24812481
struct in_addr inaddr_any;
24822482
inaddr_any.s_addr = htonl(INADDR_ANY);
24832483
struct in6_addr inaddr6_any = IN6ADDR_ANY_INIT;
24842484
fBound |= Bind(CService(inaddr6_any, GetListenPort()), BF_NONE, NetPermissionFlags::None);
24852485
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE, NetPermissionFlags::None);
24862486
}
2487-
2488-
for (const auto& addr_bind : onion_binds) {
2489-
fBound |= Bind(addr_bind, BF_EXPLICIT | BF_DONT_ADVERTISE, NetPermissionFlags::None);
2490-
}
2491-
24922487
return fBound;
24932488
}
24942489

24952490
bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
24962491
{
24972492
Init(connOptions);
24982493

2499-
if (fListen && !InitBinds(connOptions.vBinds, connOptions.vWhiteBinds, connOptions.onion_binds)) {
2494+
if (fListen && !InitBinds(connOptions)) {
25002495
if (clientInterface) {
25012496
clientInterface->ThreadSafeMessageBox(
25022497
_("Failed to listen on any port. Use -listen=0 if you want this."),

src/net.h

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -768,6 +768,9 @@ class CConnman
768768
std::vector<NetWhitebindPermissions> vWhiteBinds;
769769
std::vector<CService> vBinds;
770770
std::vector<CService> onion_binds;
771+
/// True if the user did not specify -bind= or -whitebind= and thus
772+
/// we should bind on `0.0.0.0` (IPv4) and `::` (IPv6).
773+
bool bind_on_any;
771774
bool m_use_addrman_outgoing = true;
772775
std::vector<std::string> m_specified_outgoing;
773776
std::vector<std::string> m_added_nodes;
@@ -962,10 +965,7 @@ class CConnman
962965

963966
bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
964967
bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
965-
bool InitBinds(
966-
const std::vector<CService>& binds,
967-
const std::vector<NetWhitebindPermissions>& whiteBinds,
968-
const std::vector<CService>& onion_binds);
968+
bool InitBinds(const Options& options);
969969

970970
void ThreadOpenAddedConnections();
971971
void AddAddrFetch(const std::string& strDest);

test/functional/feature_bind_extra.py

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2014-2021 The Bitcoin Core developers
3+
# Distributed under the MIT software license, see the accompanying
4+
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5+
"""
6+
Test starting bitcoind with -bind and/or -bind=...=onion and confirm
7+
that bind happens on the expected ports.
8+
"""
9+
10+
import sys
11+
12+
from test_framework.netutil import (
13+
addr_to_hex,
14+
get_bind_addrs,
15+
)
16+
from test_framework.test_framework import (
17+
BitcoinTestFramework,
18+
SkipTest,
19+
)
20+
from test_framework.util import (
21+
PORT_MIN,
22+
PORT_RANGE,
23+
assert_equal,
24+
rpc_port,
25+
)
26+
27+
class BindExtraTest(BitcoinTestFramework):
28+
def set_test_params(self):
29+
self.setup_clean_chain = True
30+
# Avoid any -bind= on the command line. Force the framework to avoid
31+
# adding -bind=127.0.0.1.
32+
self.bind_to_localhost_only = False
33+
self.num_nodes = 2
34+
35+
def setup_network(self):
36+
# Override setup_network() because we want to put the result of
37+
# p2p_port() in self.extra_args[], before the nodes are started.
38+
# p2p_port() is not usable in set_test_params() because PortSeed.n is
39+
# not set at that time.
40+
41+
# Due to OS-specific network stats queries, we only run on Linux.
42+
self.log.info("Checking for Linux")
43+
if not sys.platform.startswith('linux'):
44+
raise SkipTest("This test can only be run on Linux.")
45+
46+
loopback_ipv4 = addr_to_hex("127.0.0.1")
47+
48+
# Start custom ports after p2p and rpc ports.
49+
port = PORT_MIN + 2 * PORT_RANGE
50+
51+
# Array of tuples [command line arguments, expected bind addresses].
52+
self.expected = []
53+
54+
# Node0, no normal -bind=... with -bind=...=onion, thus only the tor target.
55+
self.expected.append(
56+
[
57+
[f"-bind=127.0.0.1:{port}=onion"],
58+
[(loopback_ipv4, port)]
59+
],
60+
)
61+
port += 1
62+
63+
# Node1, both -bind=... and -bind=...=onion.
64+
self.expected.append(
65+
[
66+
[f"-bind=127.0.0.1:{port}", f"-bind=127.0.0.1:{port + 1}=onion"],
67+
[(loopback_ipv4, port), (loopback_ipv4, port + 1)]
68+
],
69+
)
70+
port += 2
71+
72+
self.extra_args = list(map(lambda e: e[0], self.expected))
73+
self.add_nodes(self.num_nodes, self.extra_args)
74+
# Don't start the nodes, as some of them would collide trying to bind on the same port.
75+
76+
def run_test(self):
77+
for i in range(len(self.expected)):
78+
self.log.info(f"Starting node {i} with {self.expected[i][0]}")
79+
self.start_node(i)
80+
pid = self.nodes[i].process.pid
81+
binds = set(get_bind_addrs(pid))
82+
# Remove IPv6 addresses because on some CI environments "::1" is not configured
83+
# on the system (so our test_ipv6_local() would return False), but it is
84+
# possible to bind on "::". This makes it unpredictable whether to expect
85+
# that bitcoind has bound on "::1" (for RPC) and "::" (for P2P).
86+
ipv6_addr_len_bytes = 32
87+
binds = set(filter(lambda e: len(e[0]) != ipv6_addr_len_bytes, binds))
88+
# Remove RPC ports. They are not relevant for this test.
89+
binds = set(filter(lambda e: e[1] != rpc_port(i), binds))
90+
assert_equal(binds, set(self.expected[i][1]))
91+
self.stop_node(i)
92+
self.log.info(f"Stopped node {i}")
93+
94+
if __name__ == '__main__':
95+
BindExtraTest().main()

test/functional/test_runner.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@
139139
'interface_zmq.py',
140140
'rpc_invalid_address_message.py',
141141
'interface_bitcoin_cli.py',
142+
'feature_bind_extra.py',
142143
'mempool_resurrect.py',
143144
'wallet_txn_doublespend.py --mineblock',
144145
'tool_wallet.py --legacy-wallet',

0 commit comments

Comments
 (0)